package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.Logininfo;
import com.xmg.p2p.base.service.ILogininfoService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * lcd  2020/5/6
 * Description:
 */
@Controller
public class RegisterController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ILogininfoService logininfoService;

    @RequestMapping(value = "register",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult register(String username,String password){
        JSONResult jsonResult = new JSONResult();
        try{
            logininfoService.register(username,password);
            jsonResult.setMsg("注册成功");
        }catch (RuntimeException e){
            e.printStackTrace();
            jsonResult.setMsg("注册失败");
            jsonResult.setSuccess(false);
        }
        return jsonResult;
    }
    @RequestMapping("checkUsername")
    @ResponseBody
    public Boolean checkUsername(String username){
        return !logininfoService.checkUsername(username);
    }

    //前台登陆
    @RequestMapping("login")
    @ResponseBody
    public JSONResult login(String username, String password, HttpServletRequest request){
        JSONResult jsonResult = new JSONResult();
        Logininfo login = logininfoService.login(username, password, request.getRemoteAddr(),Logininfo.USER_CLIENT);
        if (login != null) {
            jsonResult.setMsg("登陆成功");
        }else {
            jsonResult.setSuccess(false);
            jsonResult.setMsg("帐号或密码错误");
        }
        return jsonResult;
    }

    @RequestMapping("u")
    @ResponseBody
    public Logininfo get(){
        return UserContext.getLogininfo();
    }
}
